package org.jiuling.youbianku;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import org.jiuling.basics.converter.StringConvert;
import org.jiuling.basics.enums.HttpResponseStatusEnum;
import org.jiuling.basics.validation.ObjectVerify;
import org.jiuling.request.http.HttpRequest;
import org.jiuling.request.http.factory.HttpRequestFactory;
import org.jiuling.request.http.model.HttpRequestParam;
import org.jiuling.request.http.model.HttpResponse;
import org.jiuling.youbianku.config.YouBianKuConfig;
import org.jiuling.youbianku.exception.YouBianKuException;
import org.jiuling.youbianku.model.StreetModel;
import org.jiuling.youbianku.model.YouBianKuResponseModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 邮编库搜索街道
 * @author 紫灵
 * @date 2024年08月21日 16时04分34秒
 */
public class YouBianKuSearchStreet {

    /** 邮编库配置 */
    private final YouBianKuConfig youBianKuConfig;
    private final String URL = "https://api.youbianku.com/api/search_street_custom.php";

    public YouBianKuSearchStreet(YouBianKuConfig youBianKuConfig) {
        this.youBianKuConfig = youBianKuConfig;
    }

    /**
     * 搜索街道
     * @param address 地址
     * @return 邮编库响应模型
     * @throws YouBianKuException 邮编库异常
     */
    public YouBianKuResponseModel<StreetModel> searchStreet(String address) throws YouBianKuException {
        try {
            HttpRequest httpRequest = HttpRequestFactory.openHttpRequest(URL);
            httpRequest.setHttpRequestParam(
                    new HttpRequestParam()
                    .add("address",address)
                    .add("key",youBianKuConfig.getKey())
            );

            HttpResponse httpResponse = httpRequest.send();
            if (httpResponse.getHttpResponseStatus() != HttpResponseStatusEnum.OK){
                throw new YouBianKuException(httpResponse.getErrorBody());
            }

            JSONObject httpRequestResponse = JSON.parseObject(httpRequest.send().getBody());
            JSONArray resultsJsonArray = httpRequestResponse.getJSONArray("results");
            String msg = httpRequestResponse.getString("msg");
            if (!"查询成功".equals(msg)){
                throw new YouBianKuException(StringConvert.format("地址：{}查询失败！","{}",address));
            }
            if (ObjectVerify.isNull(resultsJsonArray) || resultsJsonArray.isEmpty()){
                throw new YouBianKuException(msg);
            }

            YouBianKuResponseModel<StreetModel> streetModelYouBianKuResponseModel = new YouBianKuResponseModel<>();
            streetModelYouBianKuResponseModel.setMsg(msg);
            streetModelYouBianKuResponseModel.setCount(httpRequestResponse.getInteger("count"));
            streetModelYouBianKuResponseModel.setRemaincount(httpRequestResponse.getInteger("remaincount"));
            List<StreetModel> streetModelList = new ArrayList<>();
            for (int i = 0; i < resultsJsonArray.size(); i++){
                JSONObject jsonObject = resultsJsonArray.getJSONObject(i);
                StreetModel streetModel = new StreetModel();
                streetModel.setProvince(jsonObject.getString("province"));
                streetModel.setProvinceCode(jsonObject.getLong("province_code"));
                streetModel.setCity(jsonObject.getString("city"));
                streetModel.setCityCode(jsonObject.getLong("city_code"));
                streetModel.setArea(jsonObject.getString("area"));
                streetModel.setAreaCode(jsonObject.getLong("area_code"));
                streetModel.setStreet(jsonObject.getString("street"));
                streetModel.setStreetCode(jsonObject.getLong("street_code"));
                streetModel.setVillage(jsonObject.getString("village"));
                streetModel.setVillageCode(jsonObject.getLong("village_code"));
                streetModel.setAddress(jsonObject.getString("address"));
                streetModelList.add(streetModel);
            }
            streetModelYouBianKuResponseModel.setResultList(streetModelList);
            return streetModelYouBianKuResponseModel;
        } catch (IOException e) {
            throw new YouBianKuException(e.getLocalizedMessage());
        } catch (JSONException e){
            throw new YouBianKuException(StringConvert.format("响应数据格式不正确！->{}",e.getLocalizedMessage()));
        }
    }

    public static void main(String[] args) throws YouBianKuException {
//        String key = "MjAyNC04LTIxd3d3eW91Ymlhbmt1MjAyNC04LTIx";
        String key = "MjAyNC05LTE0d3d3eW91Ymlhbmt1MjAyNC05LTE0";
        YouBianKuSearchStreet youBianKuSearchStreet = new YouBianKuSearchStreet(YouBianKuConfig.builder().addKey(key).build());
        YouBianKuResponseModel<StreetModel> a = youBianKuSearchStreet.searchStreet("成都市高新区和平路戛纳湾滨江3号");
        System.out.println(JSON.toJSONString(a));
    }

}

